package org.example.aienglishapp.service.article;

import jakarta.transaction.Transactional;
import org.example.aienglishapp.config.others.RedisService;
import org.example.aienglishapp.dto.article.ArticleConverter;
import org.example.aienglishapp.dto.article.ArticleDTO;
import org.example.aienglishapp.entity.article.Article;
import org.example.aienglishapp.mapper.article.ArticleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Transactional
@Service
public class ArticleService {

    private static final Logger logger = LoggerFactory.getLogger(ArticleService.class);

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TranslationService translationService;

    @Autowired
    private RedisService redisService;  // 注入 RedisService

    private static final String ARTICLE_PREFIX = "article:";  // Redis 缓存的前缀

    // 上传文章
    public void addNewArticle(ArticleDTO articleDTO) {
        logger.info("Received ArticleDTO: {}", articleDTO);

        // 转换 DTO 到实体
        Article article = ArticleConverter.toEntity(articleDTO);
        logger.info("Converted DTO to Article entity: {}", article);

        // 插入文章到数据库
        articleMapper.insertArticle(article);
        logger.info("Inserted article with ID: {}", article.getArticleId());

        // 检查文章标题长度是否符合要求
        if (article.getTitle() == null || article.getTitle().length() > 100) {
            throw new IllegalArgumentException("文章标题不能超过100个字符");
        }
        // 检查文章正文长度是否符合要求
        if (article.getOriginalText() == null || article.getOriginalText().length() > 5000) {
            throw new IllegalArgumentException("文章正文不能超过5000个字符");
        }

        // 将生成的 ID 设回 DTO
        articleDTO.setArticleId(article.getArticleId());

        // 将文章存入 Redis 中
        redisService.set(ARTICLE_PREFIX + article.getArticleId(), articleDTO);
    }

    // 根据 ID 获取文章，首先从 Redis 获取，如果 Redis 中没有，再从数据库获取
    public ArticleDTO getArticleById(Long id) {
        // 先从 Redis 获取文章
        ArticleDTO articleDTO = (ArticleDTO) redisService.get(ARTICLE_PREFIX + id);

        if (articleDTO == null) {
            // 如果 Redis 中没有，再从数据库中获取
            Article article = articleMapper.getArticleById(id);
            articleDTO = ArticleConverter.toDTO(article);

            // 如果文章存在，将其存入 Redis
            if (articleDTO != null) {
                redisService.set(ARTICLE_PREFIX + id, articleDTO);
            }
        }

        return articleDTO;
    }

    // 获取所有文章
    public List<ArticleDTO> getAllArticles() {
        List<Article> articles = articleMapper.getAllArticles();
        return articles.stream()
                .map(ArticleConverter::toDTO)
                .collect(Collectors.toList());
    }

    // 更新文章
    public void updateArticle(ArticleDTO articleDTO) {
        logger.info("Updating article with ID: {}", articleDTO.getArticleId());

        // 转换 DTO 到实体
        Article article = ArticleConverter.toEntity(articleDTO);

        // 更新数据库中的文章
        articleMapper.updateArticle(article);

        // 更新 Redis 中的缓存
        redisService.set(ARTICLE_PREFIX + articleDTO.getArticleId(), articleDTO);
        logger.info("Article with ID: {} updated and Redis cache refreshed", articleDTO.getArticleId());
    }

    // 删除文章
    public void deleteArticle(Long id) {
        logger.info("Deleting article with ID: {}", id);

        // 删除数据库中的文章
        articleMapper.deleteArticle(id);

        // 删除 Redis 中的缓存
        redisService.delete(ARTICLE_PREFIX + id);

        // 同时删除与该文章相关的翻译记录
        translationService.deleteTranslationByArticleId(id);
        logger.info("Article with ID: {} deleted from database and Redis cache", id);
    }

    // 获取最后一篇文章的 ID
    public Long getLastArticleId() {
        return articleMapper.getLastArticleId();
    }
}